#pragma once
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <functional>
#include "Log.hpp"
#include "InetAddr.hpp"
#include "Dict.hpp"

using namespace std;

const int defaultsockfd = -1;
using func_t = function<string(const string&)>;

class UdpServer
{
public:
    UdpServer(uint16_t port, func_t func)
        :_port(port),_func(func),_sockfd(defaultsockfd),_isrunning(false)
    {}

    void InitServer()
    { 
        // 创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            LOG(FATAL, "socket create fail, stringerrno: %s, errno: %d", strerror(errno), errno);
            exit(2);
        }
        LOG(INFO, "socket create success, sockfd: %d", _sockfd);

        // 填充结构体字段
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        // bind ip+port
        int n = bind(_sockfd, (sockaddr*)&local, sizeof(local));
        if(n < 0)
        {
            LOG(FATAL, "bind fail, stringerrno: %s, errno: %d", strerror(errno), errno);
            exit(3);
        }
        LOG(INFO, "bind create success");
    }

    void Start()
    {
        _isrunning = true;
        while(true)
        {
            char request[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, request, sizeof(request)-1, 0, (struct sockaddr*)&peer, &len);
            if(n > 0)
            {
                request[n] = 0;
                InetAddr addr(peer);
                LOG(DEBUG, "get message from [%s:%d]: %s", addr.Ip().c_str(), addr.Port(), request);

                string response = _func(request);
                sendto(_sockfd, response.c_str(), strlen(response.c_str()), 0, (struct sockaddr*)&peer, len);
            }
        }
        _isrunning = false;
    }

    ~UdpServer()
    {}

private:
    int _sockfd;
    uint16_t _port;
    bool _isrunning;
    func_t _func;
};